import React from "react";
import { Form, Input, InputNumber, Select, Button, Space, Radio, TimePicker } from "antd";
import TheUpload from "@/components/TheUpload";
import TheDialog from "@/components/TheDialog";
import "../style/index.less";
import { apiStoreServiceLabelList, apiStoreInfoAdd, apiQueryMember } from '@/request/store'
import _ from 'lodash';
import GoBack from '@/components/TheGoBack'

class Add extends React.Component {
  inputRef = React.createRef();
  state = {
    mapData: null,
    loading: false,
    time: [],
    options: []
  };
  async componentDidMount() {
    await this.getLabelList()
    await this.getMemberList()
    const that = this;
    window.addEventListener("message", function (event) {
      if (event) {
        if (event.data.latlng) {
          event.data.latlng.lat = `${event.data.latlng.lat}`.substring(
            0,
            `${event.data.latlng.lat}`.indexOf(".") + 7
          );
          event.data.latlng.lng = `${event.data.latlng.lng}`.substring(
            0,
            `${event.data.latlng.lng}`.indexOf(".") + 7
          );
        }
        that.setState(
          {
            mapData: event.data,
          }
        );
      }
    });
  }

  getMemberList = async () => {
    let res = await apiQueryMember()
    if (res.code === 0 && res.data) {
      let data = res.data.map(v => {
        return {
          label: `${v.memberId}-${v.nickName}`,
          value: v.memberId
        }
      })
      this.setState({ options: data })
    }
  }

  getLabelList = async () => {
    let res = await apiStoreServiceLabelList({})
    if (res.code === 0 && res.data) {
      let labelList = res.data.map(v => {
        return {
          value: v.serviceLabelId,
          label: v.storeServiceName
        }
      })
      this.setState({ labelList })
    }
  }

  getFileList = (value) => {
    if (value && _.isString(value)) {
      return value.split(',').map((v, i) => {
        return {
          uid: i,
          status: 'done',
          name: `image-${i}`,
          url: v
        }
      })
    } else {
      return []
    }
  }

  getFileResult = (value, name) => {
    if (value && value.length) {
      let ids = value.map(v => {
        if (v.response && v.response.code === 0) {
          return v.response.data
        } else if (v.url) {
          return v.url
        } else {
          return ''
        }
      }).join(',')
      this.formRef.setFieldsValue({ [name]: ids });
    } else {
      this.formRef.setFieldsValue({ [name]: "" });
    }
  };

  setAreaData = (data) => {
    const { provinceName, cityName, areaName } = data;
    this.formRef.setFieldsValue({ address: data });
    this.setState({
      provinceName,
      cityName,
      areaName,
    });
  };

  selectAddress = () => {
    this.setState({
      visible: true,
    });
  };

  handleCancel = () => {
    this.setState(
      {
        visible: false,
      },
      () => {
        const { mapData } = this.state;
        if (mapData) {
          this.formRef.setFieldsValue({
            addressMapLocation: mapData.poiname,
            addressLat: mapData.latlng.lat,
            addressLnt: mapData.latlng.lng,
            addressDetail: mapData.poiaddress,
          });
          this.inputRef.current.value = mapData.poiname;
          this.setState({ inputValue: mapData.poiname });
        }
      }
    );
  };
  selectChange = value => {
    this.setState({ serviceLabelId: value })
  }
  goBack = () => {
    this.props.history.goBack()
  }
  onFinish = async value => {
    this.setState({ loading: true })
    value.storeOpenTime = this.state.time[0]
    value.storeCloseTime = this.state.time[1]
    value.serviceLabelIds = value.serviceLabelIds.join(',')
    delete (value.time)
    let res = await apiStoreInfoAdd({ ...value })
    if (res.code === 0) {
      React.$message({
        type: 'info',
        content: '新增成功'
      })
      this.goBack()
      this.setState({ loading: false })
    } else {
      this.setState({ loading: false })
    }
  }
  timeChange = (time, timeString) => {
    console.log(timeString);
    this.setState({ time: timeString })
  }
  render() {
    const { labelList, visible, serviceLabelIds, loading, options } = this.state;
    const url = `https://mapapi.qq.com/web/mapComponents/locationPicker/v/index.html?search=1&type=1&locations=45.80216,126.5358&key=5GEBZ-RHECU-SWOVM-26CNG-EBL7E-YEFWM&referer=myapp`
    return (
      <div className="settings-box">
        <GoBack title={'新增门店'} history={this.props.history} />
        <Form onFinish={this.onFinish}
              ref={(ref) => (this.formRef = ref)}
              labelCol={{
                span: 2,
              }}
              wrapperCol={{
                span: 4,
              }}
        >
          <div className="title">门店信息</div>
          <Form.Item
            rules={[{ required: true }]}
            label="门店类型"
            name={'isProprietary'}>
            <Radio.Group>
              <Radio value={'Y'}>自营</Radio>
              <Radio value={'N'}>非自营</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item label="经营类目" name="businessCategory" rules={[{ required: true }]}>
            <Select
                options={[
                  {
                    value:0,
                    label:"店铺"
                  },
                  {
                    value:1,
                    label:"酒店"
                  },
                  {
                    value:2,
                    label:"医院"
                  },
                  {
                    value:3,
                    label:"上门服务"
                  },
                ]}
                placeholder="请选择经营类目">
            </Select>
          </Form.Item>
          <Form.Item label="一级类型" name="primaryType" rules={[{ required: true }]}>
            <Select
                options={[
                  {
                    value: "shop",
                    label:"门店"
                  },
                  {
                    value: "onlineShop",
                    label:"网店"
                  },
                  {
                    value: "channelShop",
                    label:"渠道店"
                  },
                ]}
                placeholder="请选择一级类型">
            </Select>
          </Form.Item>
          <Form.Item label="二级类型" name="secondaryType" rules={[{ required: true }]}>
            <Select
                options={[
                  {
                    value: "selfSupport",
                    label: "自营"
                  },
                  {
                    value: "join",
                    label: "加盟"
                  },
                  {
                    value: "agent",
                    label: "代理"
                  },
                  {
                    value: "consignment",
                    label: "代销"
                  },
                  {
                    value: "thridParty",
                    label: "第三方"
                  },
                ]}
                placeholder="请选择二级类型">
            </Select>
          </Form.Item>
          <Form.Item
            rules={[{ required: true }]}
            label="门店名称"
            name={'storeName'}>
            <Input placeholder="请输入门店名称" maxLength={15}/>
          </Form.Item>
          <Form.Item
            rules={[{ required: true }]}
            label="联系人"
            name={'storeContacts'}>
            <Input placeholder="请输入联系人" />
          </Form.Item>
          <Form.Item
            rules={[{ required: true }]}
            label="联系电话"
            name={'userMobile'}>
            <Input placeholder="请输入联系电话" />
          </Form.Item>
          <Form.Item label="管理员" name="userId" rules={[{ required: true }]}>
            <Select
              showSearch
              optionFilterProp="label"
              filterOption={(input, option) => option.label.includes(input)}
              options={options}
              placeholder="请选择门店管理员" />
          </Form.Item>
          <Form.Item
            rules={[{ required: true }]}
            label="门店标签"
            name={'serviceLabelIds'}>
            <Select
              placeholder="请选择门店标签"
              mode="multiple"
              allowClear
              value={serviceLabelIds}
              options={labelList}
              onChange={this.selectChange}
            />
          </Form.Item>
          <Form.Item label="营业时间" rules={[{ required: true }]} name="time">
            <TimePicker.RangePicker onChange={this.timeChange} format={'HH:mm'} />
          </Form.Item>
          <Form.Item
            rules={[{ required: true }]}
            label="门店图片"
            name={'storeShowFile'}>
            <TheUpload getFileResult={value => this.getFileResult(value, 'storeShowFile')} maxSize={10} len={1} />
          </Form.Item>
          <Form.Item
            rules={[{ required: true }]}
            label="店铺环境"
            name={'storeEnvironment'}>
            <TheUpload getFileResult={value => this.getFileResult(value, 'storeEnvironment')} maxSize={10} len={4} />
          </Form.Item>
          <Form.Item
            rules={[{ required: true }]}
            label="店铺logo"
            name={'storeLogo'}>
            <TheUpload getFileResult={value => this.getFileResult(value, 'storeLogo')} maxSize={10} len={1} />
          </Form.Item>
          <div className="title">资质信息</div>
          {/* <Form.Item label="门店所在地区" name={'address'}>
            <TheArea
              ref={(ref) => (this.addressRef = ref)}
              setAreaData={this.setAreaData}
            />
          </Form.Item> */}
          <Form.Item
            rules={[{ required: true }]}
            name={"addressMapLocation"}
            label="门店地址">
            <Space>
              <input
                className="address-input"
                ref={this.inputRef}
                placeholder="请在地图上选点"
              />
              <Button onClick={this.selectAddress}>打开地图</Button>
            </Space>
          </Form.Item>
          <Form.Item
            rules={[{ required: true }]}
            name={"addressLnt"}
            label="经度">
            <InputNumber placeholder="请输入经度" />
          </Form.Item>
          <Form.Item
            rules={[{ required: true }]}
            name={"addressLat"}
            label="纬度">
            <InputNumber placeholder="请输入纬度" />
          </Form.Item>
          <Form.Item
            name={"addressDetail"}
            label="详细地址(选填)">
            <Input placeholder="请输入详细地址" />
          </Form.Item>
          <Form.Item
            rules={[{ required: true }]}
            label="营业执照"
            name={'businessLicense'}>
            <TheUpload getFileResult={value => this.getFileResult(value, 'businessLicense')} maxSize={10} len={1} />
          </Form.Item>
          <div className="title">法人信息</div>
          <Form.Item
            rules={[{ required: true }]}
            label="法人身份证正面"
            name={'corporateIdentityCardPositive'}>
            <TheUpload getFileResult={value => this.getFileResult(value, 'corporateIdentityCardPositive')} maxSize={10} len={1} />
          </Form.Item>
          <Form.Item
            rules={[{ required: true }]}
            label="法人身份证背面"
            name={'corporateIdentityCardBack'}>
            <TheUpload getFileResult={value => this.getFileResult(value, 'corporateIdentityCardBack')} maxSize={10} len={1} />
          </Form.Item>
          <Form.Item
            rules={[{ required: true }]}
            label="收款账号(支付宝)"
            name={'alipayAccount'}>
            <Input placeholder="请输入收款账号" />
          </Form.Item>
          <Form.Item
              wrapperCol={{
                offset: 2,
                span: 2
              }}
          >
            <div style={{ display: "flex", justifyContent: "center" }}>
              <Space>
                <Button onClick={this.goBack}>取消</Button>
                <Button loading={loading} type="primary" htmlType="submit">保存</Button>
              </Space>
            </div>
          </Form.Item>
        </Form>
        <TheDialog
          title=""
          width={500}
          handleCancel={this.handleCancel}
          visible={visible}
          footer={null}
        >
          <iframe
            title="map"
            style={{
              width: 400,
              height: 700,
              border: "1px solid #fafafa",
              marginLeft: "20px",
            }}
            src={url}
          />
        </TheDialog>
      </div>
    );
  }
}

export default Add;
